#!/usr/bin/env python3
"""
诊断补充润色功能
检查数据是否正确上传到数据库
"""

import sys
import os
import requests

# 添加项目路径
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))

def check_backend_connection(api_url):
    """检查后端连接"""
    print("=" * 60)
    print("1. 检查后端连接")
    print("=" * 60)

    try:
        response = requests.get(f"{api_url}/api/health", timeout=5)
        if response.status_code == 200:
            print(f"✓ 后端连接正常: {api_url}")
            return True
        else:
            print(f"✗ 后端返回错误: HTTP {response.status_code}")
            return False
    except Exception as e:
        print(f"✗ 后端连接失败: {e}")
        return False


def check_repolish_api(api_url, platform=1):
    """检查补充润色 API"""
    print("\n" + "=" * 60)
    print("2. 检查补充润色 API")
    print("=" * 60)

    try:
        # 测试获取需要润色的列表
        url = f"{api_url}/api/worker/need-repolish"
        params = {'platform': platform, 'limit': 5}

        response = requests.get(url, params=params, timeout=10)
        response.raise_for_status()
        result = response.json()

        if result.get('success'):
            total = result.get('total', 0)
            print(f"✓ API 正常，找到 {total} 个需要润色的作品")

            if total > 0:
                print(f"\n前 5 个需要润色的作品:")
                for i, work in enumerate(result.get('works', [])[:5], 1):
                    print(f"  {i}. workId={work['workId']}, "
                          f"polishStatus={work.get('polishStatus', 'null')}, "
                          f"title={work.get('title', 'N/A')[:30]}...")
            return True
        else:
            print(f"✗ API 返回失败: {result.get('message')}")
            return False

    except Exception as e:
        print(f"✗ API 调用失败: {e}")
        return False


def test_batch_update(api_url):
    """测试批量更新 API"""
    print("\n" + "=" * 60)
    print("3. 测试批量更新 API（模拟数据）")
    print("=" * 60)

    try:
        url = f"{api_url}/api/worker/batch-update-polish"

        # 构造一个测试数据（假数据，不会实际更新）
        test_data = {
            'works': [
                {
                    'platform': 1,
                    'workId': 'test_12345',
                    'databaseId': 99999999,  # 不存在的ID
                    'polishedText': '这是测试数据',
                    'polishStatus': 1,
                    'polishEngine': 'test',
                    'qualityScore': 99
                }
            ]
        }

        response = requests.post(url, json=test_data, timeout=10)
        response.raise_for_status()
        result = response.json()

        if result.get('success'):
            print(f"✓ API 调用成功")
            print(f"  更新: {result.get('updated', 0)} 条")
            print(f"  失败: {result.get('failed', 0)} 条")
            print(f"  (测试数据应该失败1条，因为ID不存在)")
            return True
        else:
            print(f"✗ API 返回失败: {result.get('message')}")
            return False

    except Exception as e:
        print(f"✗ API 调用失败: {e}")
        return False


def check_database(api_url, work_id):
    """检查数据库中特定作品的润色状态"""
    print("\n" + "=" * 60)
    print(f"4. 检查数据库中的润色状态 (workId={work_id})")
    print("=" * 60)

    try:
        # 通过后端 API 查询（需要后端提供查询接口）
        # 这里我们通过 need-repolish 来反向验证
        url = f"{api_url}/api/worker/need-repolish"
        params = {'platform': 1, 'limit': 1000}

        response = requests.get(url, params=params, timeout=10)
        result = response.json()

        if result.get('success'):
            works = result.get('works', [])
            found = None
            for work in works:
                if work['workId'] == work_id:
                    found = work
                    break

            if found:
                print(f"✓ 找到作品，状态：")
                print(f"  workId: {found['workId']}")
                print(f"  polishStatus: {found.get('polishStatus', 'null')}")
                print(f"  title: {found.get('title', 'N/A')}")
                print(f"\n  说明：此作品仍在「需要润色」列表中")
                print(f"  可能原因：")
                print(f"    1. 润色数据尚未上传")
                print(f"    2. 上传失败")
                print(f"    3. 后端更新逻辑有问题")
                return False
            else:
                print(f"✓ 作品不在「需要润色」列表中")
                print(f"  说明：润色可能已成功")
                return True

    except Exception as e:
        print(f"✗ 查询失败: {e}")
        return False


def main():
    print("补充润色功能诊断工具")
    print("=" * 60)

    # 从命令行参数或环境变量获取配置
    api_url = os.getenv('API_URL', 'http://localhost:8001')

    if len(sys.argv) > 1:
        api_url = sys.argv[1]

    print(f"后端地址: {api_url}")
    print()

    # 执行检查
    results = []

    results.append(("后端连接", check_backend_connection(api_url)))
    results.append(("补充润色API", check_repolish_api(api_url)))
    results.append(("批量更新API", test_batch_update(api_url)))

    # 如果提供了 workId，检查特定作品
    if len(sys.argv) > 2:
        work_id = sys.argv[2]
        results.append((f"作品状态 ({work_id})", check_database(api_url, work_id)))

    # 总结
    print("\n" + "=" * 60)
    print("诊断总结")
    print("=" * 60)

    for name, success in results:
        status = "✓ 正常" if success else "✗ 异常"
        print(f"{name:20s}: {status}")

    print("\n建议:")
    if not all(r[1] for r in results):
        print("  1. 检查后端服务是否正常运行")
        print("  2. 检查 API 路径是否正确")
        print("  3. 查看后端日志获取详细错误")
    else:
        print("  所有检查通过！")
        print("  如果仍然看不到润色结果，请：")
        print("    1. 检查完整的 Worker 日志")
        print("    2. 查看后端数据库")
        print("    3. 确认润色数据是否已上传")


if __name__ == '__main__':
    main()
